<template>
  <div>
    <div class="search-song-wrapper">
      <div class="search-input">
        <div class="label">歌曲搜索</div>
        <div class="input">
          <el-autocomplete
            @select="fetchSearchSong"
            :fetch-suggestions="querySearchAsync"
            :select-when-unmatched="true"
            style="width: 274px"
            v-model="searchKey"
          ></el-autocomplete>
          <el-button type="primary" @click="fetchSearchSong">搜索</el-button>
        </div>
      </div>
      <div class="common-list">
        <ul>
          <li v-for="(item, idx) in searchList" :key="idx">
            <div class="album">
              <img v-lazy="{ src: item.al.picUrl, loading: defaultImg, error: defaultImg }" alt="" />
            </div>
            <div class="song-info">
              <div class="song-name">
                {{ item.name }}
              </div>
              <div class="song-artist">
                {{ getArtist(item.ar) }}
              </div>
            </div>
            <div class="song-order">
              <el-button @click.stop="setMusicId(item)">点歌</el-button>
            </div>
          </li>
        </ul>
        <ShowLoading :loading="loading" />
      </div>
    </div>
    <!-- <audio :src="musicUrl" autoplay="autoplay" controls="controls"></audio> -->
  </div>
</template>
<script>
import { CommonEnum } from '@/enums'
import { computed, onMounted, reactive, ref, toRefs } from 'vue'
import { useStore } from 'vuex'
import { useObserverHook } from '@/hooks'
import { ElMessage } from 'element-plus'
export default {
  setup() {
    const store = useStore()
    const searchKey = ref('')
    const defaultImg = require('../../../../assets/images/loading.gif')

    let state = reactive({
      searchList: [],
      songCount: 0,
      pageNum: CommonEnum.PAGE.pageNum,
      pageSize: CommonEnum.PAGE.pageSize,
      loading: false
    })
    useObserverHook('#' + CommonEnum.LOADING_ID, entries => {
      console.log(entries)
      if (!state.loading && entries[0].isIntersecting) {
        state.pageNum = state.pageNum + 1
        console.log(state.pageNum)
        loadMoreSong()
      }
    })
    const loadMoreSong = async () => {
      if (!searchKey.value) return
      state.loading = true
      console.log(state.pageNum)
      const res = await store.dispatch('fetchSearchSong', { keywords: searchKey.value, offset: state.pageNum, limit: state.pageSize })
      let result = res.result.songs || []
      if (result.length) {
        state.searchList = [...state.searchList, ...result]
        if (state.searchList.length < state.pageSize) {
          state.loading = false
        }
      }
      state.songCount = res.result.songCount
      state.loading = false
    }
    const querySearchAsync = async (queryString, cb) => {
      if (!queryString) {
        let hotList = await store.dispatch('_getSearchHot')
        if (hotList) {
          hotList = hotList.data.map(v => {
            return {
              value: v.searchWord
            }
          })
          cb([...hotList])
        } else {
          cb([])
        }
      } else {
        let suggestList = await store.dispatch('_getSearchSuggest', { keywords: queryString })
        if (suggestList) {
          cb([...suggestList])
        } else {
          cb([])
        }
      }
    }
    const fetchSearchSong = async () => {
      if (!searchKey.value) return
      state.loading = true
      state.searchList = []
      state.pageNum = 1
      console.log(state.pageNum)
      const res = await store.dispatch('fetchSearchSong', { keywords: searchKey.value, offset: state.pageNum, limit: state.pageSize })
      let result = res.result.songs || []
      state.searchList = result
      state.songCount = res.result.songCount
      state.loading = false
    }
    const _getSongCanUse = async id => {
      const res = await store.dispatch('_getSongCanUse', { id })
      console.log(res)
      if (res) {
        return res.success
      }
    }
    const _postAddSongOrder = async item => {
      let params = {
        songId: item.id,
        name: item.name,
        picUrl: item.al.picUrl,
        artist: getArtist(item.ar),
        duration: item.dt
      }
      const res = await store.dispatch('_postAddSongOrder', params)
      console.log(res)
      if (res) {
        // await store.dispatch('_postAddOrderHistory', params)
        ElMessage.success({
          message: '添加成功'
        })
        store.dispatch('updateOrderList')
      }
    }
    const setMusicId = async item => {
      let res = await _getSongCanUse(item.id)
      console.log(res)
      if (res) {
        // let currentSong = {
        //   artist: getArtist(item.ar),
        //   name: item.name,
        //   picUrl: item.al.picUrl,
        //   id: item.id
        // }
        // store.commit('SET_STATE', { key: 'songInfo', value: currentSong })
        // store.commit('SET_ORDER_LIST', item)
        _postAddSongOrder(item)
      }
    }
    const getArtist = item => {
      return item.map(v => v.name).join('&')
    }
    onMounted(() => {})
    return {
      ...toRefs(state),
      searchKey,
      fetchSearchSong,
      setMusicId,
      getArtist,
      defaultImg,
      querySearchAsync
    }
  }
}
</script>
<style lang="scss">
@import '@/style/mixin.scss';
.search-song-wrapper {
  height: 100%;
  .search-input {
    background: #fff;
    margin: 0 0 10px 0;
    padding-bottom: 12px;
    .label {
      padding: 12px;
      text-align: left;
      font-size: 18px;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .input {
      display: flex;
      justify-content: center;
      padding: 0 12px 0 12px;
    }
    .el-input__inner {
      border-radius: 4px 0 0 4px;
      border-right: none;
    }
    .el-button--small {
      border-radius: 0 4px 4px 0;
    }
  }
}
</style>
